//
//  LoginViewController.m
//  ProjectTemplet
//
//  Created by HouKavin on 15/12/31.
//  Copyright © 2015年 HouKavin. All rights reserved.
//

#import "LoginViewController.h"
#import "GlobalReference.h"

@interface LoginViewController ()

@end

@implementation LoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self LodeView];
}

//加载登录界面
-(void)LodeView{
    self.loginName.layer.borderColor = kGrayColor.CGColor;
    self.loginName.layer.borderWidth = 1;
    self.loginName.leftViewMode = UITextFieldViewModeAlways;
    self.loginName.leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 60, 44)];
    
    UILabel* imgUser = [[UILabel alloc] initWithFrame:CGRectMake(11, 2, 60, 40)];
    imgUser.text = @"帐号";
    [self.loginName.leftView addSubview:imgUser];
    
    self.password.layer.borderColor = kGrayColor.CGColor;
    self.password.layer.borderWidth = 1;
    self.password.leftViewMode = UITextFieldViewModeAlways;
    self.password.leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 60, 44)];
    
    UILabel* imgPwd = [[UILabel alloc] initWithFrame:CGRectMake(11, 2, 60, 40)];
    imgPwd.text=@"密码";
    [self.password.leftView addSubview:imgPwd];
    
    kViewRadius(self.loginBtn,5);
    [self loadDefaults];
}


//登录
- (IBAction)loginBtnClick:(id)sender {
    [self.view endEditing:YES];//关闭键盘
    //获取账号信息
    NSString * username = [StringUtil trim:self.loginName.text];
    //获取密码信息
    NSString * passwd = self.password.text;
    
    //判断账号、密码不能为空
    if ([StringUtil isEmpty: username]) {
        [CommonUtil showErrorMessage:@"请输入用户名"];
        return ;
    }
    if ([StringUtil isEmpty: passwd]) {
        [CommonUtil showErrorMessage:@"请输入密码"];
        return ;
    }
    
    if ([StringUtil isEmpty:[AppInfo sharedInstance].baseURL]) {
        [CommonUtil showErrorMessage:@"请先设置ip地址"];
        return;
    }
    
    [CommonUtil showLoadingWithMessage:@"正在登陆"];
    //传递的参数（字典类型、类似于JAVA中的MAP）
    NSDictionary *parameters = [NSDictionary dictionaryWithObjectsAndKeys:
                                username, @"username",
                                passwd, @"password",
                                nil];
    
    //请求登录的地址
    NSString *url=@"Login";
    //HTTP请求判断登录信息，服务端返回的是一个由MAP转换成德JSON信息
    [MyAFNetworking Post:url
           addParameters:parameters
          andSucessBlock:^(NSURLSessionDataTask *operation, id responseObject) {
              //停止loading效果展示
              [CommonUtil dismissLoading];
              NSLog(@"获得的数据是  %@",responseObject);
              //[responseObject valueForKeyPath:@""]返回的是一个id类型的数据，可以用任何类型接收
              NSString *success = [responseObject valueForKeyPath:@"ifSuccess"];
              if ([success isEqualToString:@"1"]) {
                  //根据“记住密码”checkbox的勾选状态确定是否保存账号和密码
                  NSString *savedUserName;
                  NSString *savedPassword;
                  
                  if (self.remeberBtn.selected) {//需要记住账号的密码
                      savedUserName = username;
                      savedPassword = passwd;
                  }else{//如果选择不“记住密码”，则不保存用户的账号密码信息，从而使得自动登陆选项也会无效
                      savedUserName = @"";
                      savedPassword = @"";
                  }
                  
                  //保存账号密码信息
                  [self saveDefaultsWithUserName:savedUserName
                                     andPassword:savedPassword
                                     andRemember:self.remeberBtn.selected];
                  //AppInfo中的UserName，一定要设置成输入框中的内容
                  [AppInfo sharedInstance].userId = username;
                  //AppInfo中的PassWord，一定要设置成输入框中的内容
                  [AppInfo sharedInstance].userPwd = passwd;
                  [AppInfo sharedInstance].userName = [responseObject valueForKeyPath:@"usrnam"];
                  [AppInfo sharedInstance].unitName = [responseObject valueForKeyPath:@"unitnam"];
                  [AppInfo sharedInstance].orgName = [responseObject valueForKeyPath:@"orgName"];
                  
                  [self performSegueWithIdentifier:@"LoginSegue" sender:self];
              }else {
                  [CommonUtil showAlert:@"用户或密码错误!"];
              }
          }
         andFailureBlock:^(NSURLSessionDataTask *operation, NSError *error) {
             [CommonUtil dismissLoading];
             [CommonUtil showErrorMessage:@"连接服务器出错!"];
             NSLog(@"请求错误:%@", [error userInfo]);
         }];
}


//获取默认的登陆设置
- (void)loadDefaults{
    //获取用户轻量级的数据持久化信息
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    
    //获取账号信息
    NSString *userName = [defaults objectForKey:@"userName"];
    if(userName != nil) {
        self.loginName.text = userName;
    }
    
    //获取密码信息
    NSString *passWord = [defaults objectForKey:@"passWord"];
    if(passWord != nil) {
        self.password.text = passWord;
    }
    
    //获取是否保存密码
    BOOL isRemember=[defaults boolForKey:@"isRemember"];
    if(isRemember){
        [self.remeberBtn onSelected:self];
    }else{
        [self.remeberBtn offSelected:self];
    }
    
    //获取ip地址信息
    NSString *baseUrl = [defaults objectForKey:@"baseUrl"];
    if(![StringUtil isEmpty:baseUrl]) {
        [AppInfo sharedInstance].baseURL = baseUrl;
    }
}

//保存登陆设置
- (void)saveDefaultsWithUserName:(NSString *)userName
                     andPassword:(NSString *)password
                     andRemember:(BOOL)isRemember{
    //获取用户轻量级的数据持久化信息
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    //保存账号
    [defaults setObject:userName forKey:@"userName"];
    //保存密码
    [defaults setObject:password forKey:@"passWord"];
    //保存是否保存账号和密码信息
    [defaults setBool:isRemember forKey:@"isRemember"];
    //保存能够成功登陆的IP地址
    [defaults setObject:[AppInfo sharedInstance].baseURL forKey:@"baseUrl"];
    NSLog(@"baseUrl222 %@",[AppInfo sharedInstance].baseURL);
    [defaults synchronize];
    
}

/*
//输入框移动
-(void)textFieldDidBeginEditing:(UITextField *)textField{
    NSLog(@"键盘代理调用");
    CGFloat keyboardHeight = 216.0f;
    if (self.view.frame.size.height - keyboardHeight <= textField.frame.origin.y + textField.frame.size.height) {
        CGFloat y = textField.frame.origin.y - (self.view.frame.size.height - keyboardHeight - textField.frame.size.height - 5);
        [UIView beginAnimations:@"srcollView" context:nil];
        [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
        [UIView setAnimationDuration:0.275f];
        self.view.frame = CGRectMake(self.view.frame.origin.x, -y, self.view.frame.size.width, self.view.frame.size.height);
        [UIView commitAnimations];
    }
}


//输入框复位
-(void)textFieldDidEndEditing:(UITextField *)textField{
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    [UIView setAnimationDuration:0.275f];
    self.view.frame = CGRectMake(self.view.frame.origin.x, 0, self.view.frame.size.width, self.view.frame.size.height);
    [UIView commitAnimations];
}
 
*/

//取消第一响应
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    [self.loginName resignFirstResponder];
    [self.password resignFirstResponder];
    return YES;
}


-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}



@end
